package com.zpark;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @PackageName: com.zpark
 * @ClassName: DOMParseDemo
 * @Description: dom解析器
 * @author: RZS
 * @date: 2021/8/14  11:21
 */
public class DOMParseDemo {
    public static void main(String[] args) throws Exception {
        /*
            1):表示出需要被操作的XML文件的路径,注意是文件的路径,不是文件所在的目录.
                File f = new File(...);
            2):根据DocumentBuilderFactory类,来获取DocumentBuilderFactory对象.
                注意:工厂设计模式往往体现着单例设计模式.
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
            3):根据DocumentBuilderFactory对象,构建DocumentBuilder对象.
                注意:XxxFactory,就是用来创建Xxx对象的.
                DocumentBuilder build = factory .newDocumentBuilder();
            4):根据DocumentBuidler对象,构建Document对象.
                Document doc = build.parse(f);
         */
        // 获取xml文件路径
        String path = DOMParseDemo.class.getClassLoader().getResource("domDemo.xml").getPath();
        // 由于路径中包含中文，所以需要对路径解析解码
        path = URLDecoder.decode(path, "utf-8");

        File file = new File(path);
        // 获取DocumentBuilderFactory对象
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // 根据DocumentBuilderFactory对象,构建DocumentBuilder对象
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // 根据DocumentBuidler对象,构建Document对象
        Document document = documentBuilder.parse(path);

        // 获取给定标签名元素内容
        NodeList student = document.getElementsByTagName("student");
        for (int i = 0; i < student.getLength(); i++) {
            // 获取节点对象
            Node node = student.item(i);
            // 将node转为element，node为element父接口
            Element element = (Element)node;
            // 根据标签名字获取标签的text值
            String firstname = element.getElementsByTagName("firstname").item(0).getTextContent();
            System.out.println(firstname);
        }
    }
}
